const express = require('express');
const data = require('./newsData')
const fs = require('fs')
const path = require('path');
const multer = require('multer');
const Jimp = require('jimp');

const app = express();
const port = 7100;

//对post请求的参数进行处理
app.use(express.json());
app.use(express.urlencoded({ extended: true }));

/* 获取最新新闻 */
app.get('/news_latest',(req,res)=>{
    res.send({
        date:'20180312',
        stories:data.stories,
        top_stories:data.top_stories
    })
})
/* 获取以往新闻 */
app.get('/news_before',(req,res)=>{
    let { time } = req.query
    res.send({
        date:time,
        stories:data.before_stories
    })
})
/* 获取新闻详情信息 */
app.get('/news_info',(req,res)=>{
    let { id } = req.query
    res.send(data.news_info)
})
/* 获取新闻点赞信息 */
app.get('/story_extra',(req,res)=>{
    let { id } = req.query
    res.send(data.story_extra)
})

/* 获取手机验证码 */
let verificationCode, tempPhone;
app.post('/phone_code',(req,res)=>{
    const { phone } = req.body
    tempPhone = +phone
    const sendTime = new Date().toLocaleString()
    //verificationCode = Math.random().toFixed(6) * 1000000 
    verificationCode = Math.floor(Math.random() * 900000) + 100000
    const info = `手机号 ${phone} 的用户于 ${sendTime} 发送短信验证码: ${verificationCode}`
    
    // 创建可写流
    const writeStream = fs.createWriteStream(path.join(__dirname, 'code.txt'), { flags: 'a' })
    // 每次写入信息
    function writeToCodeFile(info) {
        writeStream.write(info + '\n', 'utf8', (err) => {
            if (err) {
                //console.error(err);
                res.status(500).send('生成信息文件时出错');
            } else {
                //console.log('成功生成信息文件');
                res.send({
                    code:0,
                    codeText:'',
                    vCode:verificationCode
                })
            }
        });
    }
    writeToCodeFile(info)
    setTimeout(()=>{ verificationCode = null },30000) //在30s后验证码无效
})

/* 用户登录 */
let attempts = 0, maxAttempts = 6;
app.post('/login',(req,res)=>{
    let { phone,code } = req.body
    if(verificationCode === +code && tempPhone === +phone && attempts < maxAttempts){ //验证码只能尝试5次
        attempts = 0
        res.send({
            code:0,
            codeText:'',
            token:'j9NGjM0dlS'
        })
    }else{
        attempts++
        res.send({ code:1 })
    }
})

/* 对图片进行处理 */
app.use(express.static(path.join(__dirname, 'public')));// 设置静态文件目录
/* 处理图片资源的路由 */
app.get('/images/:imageName', (req, res) => {
    const imageName = req.params.imageName; //获取
    res.sendFile(path.join(__dirname, 'public', 'images', imageName));
});

/* 获取登录者信息 */
let userinfo = {
    id:1,
    name:'T-bag',
    phone:tempPhone,
    pic:'http://localhost:7100/images/dog.png'
}
app.get('/user_info',(req,res)=>{
    const authHeader = req.headers['authorization'];
    if(authHeader){
        res.send({
            code:0,
            codeText:'OK',
            data:userinfo
        })
    }else{
        res.send({
            code:1,
            codeText:'BAD'
        })
    }
})
/* 获取收藏者收藏列表 */
app.get('/store_list',(req,res)=>{
    res.send({
        code:0,
        codeText:'OK',
        data:[
            {id:1,userId:24,news:{id:9717893,image:'https://pic2.zhimg.com/v2-5c87a645d36d140fa87df6e8ca7cb989.jpg',title:'斑马的条纹到底是干嘛用的1?',}},
            {id:2,userId:32,news:{id:9717894,image:'https://pic2.zhimg.com/v2-5c87a645d36d140fa87df6e8ca7cb989.jpg',title:'斑马的条纹到底是干嘛用的2?',}}
        ]
    })
})
app.post('/store',(req,res)=>{
    let { newsId } = req.body
    res.send({
        code:0,
        codeText:'OK'
    })
})
app.post('/store_remove',(req,res)=>{
    let { id } = req.body
    res.send({
        code:0,
        codeText:'OK'
    })
})

/* 图片上传 */
const upload = multer({ dest: 'public/uploads/' })
app.post('/upload',upload.single('file'),async (req,res)=>{ //只接受名为 'file' 的单个文件上传,且字段名操持一致。
    //console.log(req.file);
    // 读取上传的二进制文件
    const fileBuffer = fs.readFileSync(req.file.path);
    try {
        // 使用 jimp 加载二进制数据并保存为图片
        const image = await Jimp.read(fileBuffer);
        await image.writeAsync(`public/images/${req.file.originalname}`);
        res.send({
            code:0,
            codeText:'OK',
            pic:`http://localhost:7100/images/${req.file.originalname}`
        })
    }catch (e) {
        res.send({
            code:1,
            codeText:'Bad',
        })
    }
})
/* 修改用户信息 */
app.post('/user_update',(req,res)=>{
    let { username,pic } = req.body
    userinfo.name = username
    userinfo.pic = pic
    res.send({
        code:0,
        codeText:'OK'
    })
})

app.listen(port,()=>{
    console.log('知乎日报的服务端口7100已启动');
})